<template>
  <div class="land-view">
    <!--地图页面-->
    <div class="map-view">
      <div class="left-view-table">
        <landTotal :farmcount="farmcount" />
        <div class="optate-search">
          <div class="scinput">
            <el-input placeholder="请输入地块名称" clearable size="mini" v-model="searchInfo.farmLandName">
              <template #append style="padding: 0 4px;">
                <vxe-button type="text" @click="btnQuery" icon="vxe-icon-search"></vxe-button>
              </template>
            </el-input>
          </div>
          <hoverMuen @change="changeMuen" />
        </div>
        <div class="select-search-view">
          <el-select v-model="searchInfo.landGroupId"
                     @change="btnQuery"
                     :clearable="true"
                     style="width:100%;" placeholder="分组">
            <el-option
              v-for="item in landGroups"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="searchInfo.landTypeId"
                     @change="btnQuery"
                     :clearable="true"
                     style="width:100%;" placeholder="类型">
            <el-option
              v-for="item in landTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <Select v-model="searchInfo.cropId"
                  @change="btnQuery"
                  :params="{lovCode:'TANC_CROP'}"
                  :clearable="true" placeholder="作物" />
          <el-select v-model="searchInfo.landTagId"
                     @change="btnQuery"
                     :clearable="true"
                     style="width:100%;" placeholder="标签">
            <el-option
              v-for="item in landTags"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <LandList :tableData="tableData" @onClick="setMapData" @page-change="pageChangeEvent" :pageInfo="searchInfo" />
      </div>
      <mapContainer @init="initMap" @zoom="zoomMap" searchLeft="330px" searchTop="20px" @click="clickMap"  @pointerMove="pointerMove" />
      <PoiPopup v-if="showPop &&currentZoom>12" @toNext="toNext" :popOption="popObjct"   @onClose="(type)=>{showPop=type}" />

      <vxe-modal v-model="openModel"  
       mask-closable
       :draggable="false"
       :mask="false" 
       :zIndex="-1" 
       :width="winWidth" 
       :lock-scroll="false"
       @close="()=>{btnQuery()}"
       :position="{top: 60, left: 268}" >
       <template #title> 
        <vxe-icon v-if="openModelType==2" name="feedback" roll></vxe-icon>  
        <vxe-icon v-if="openModelType==1" name="check" roll></vxe-icon>  
        <vxe-icon v-if="openModelType==4" name="copy" roll></vxe-icon>  
        {{openModelType==1?'认领地块':(openModelType==2?'批量编辑地块':'土壤养分')}}
        <vxe-button v-if="openModelType==1" @click="btnDelAll" style="margin-left:20px" type="text" size="small" status="danger" icon="vxe-icon-delete">全部删除</vxe-button>
        </template>
        <template #default>
          <receiveLand ref="refReceiveLand" v-if="openModelType==1 && openModel" @eidt="eidtClick"  @close="openModel=false" /> 
          <eidtLand v-if="openModelType==2 && openModel" :farmLandId="dropFarmLandId"  @close="openModel=false" /> 
          <nutritionLand v-if="openModelType==4 && openModel"  @close="openModel=false" /> 
        </template>
      </vxe-modal>
      <div class="land-detail" v-if="showDetail">
      <land-detail :farmLandId="dropFarmLandId"
                   @clickDel="btnDel"
                   @eidt="eidtClick"
                   :farmLandNo="dropFarmLandNo"
                   :farmLandPic="dropFarmLandPic"
                    @close="showDetail=false" />
    </div>
    </div>
  </div>
</template>
<script setup>
import {nextTick, ref, watch, onActivated, reactive, onMounted, toRefs, watchEffect} from 'vue'
import {getLandGroupList, getLandTagsList, getLandList,getMinLandList} from '@/api/plant'
import {getLandTypeList, getFarmCount,releaseFarmland} from '@/api/gis'
import {WktToPolygon } from '@/components/Map/utils/geoToWkt';
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"
import Graphic from "@arcgis/core/Graphic"
import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
import LandList from './components/landList.vue'
import landTotal from './components/landTotal.vue'
import hoverMuen from './components/hoverMuen.vue'
import {useUserStore} from '@/pinia/modules/user'
import Select from "@/components/custom/select.vue"
import  mapContainer from '@/components/Map/index.vue'
import PoiPopup from '@/components/Map/components/PoiPopup.vue';
  import Point from '@arcgis/core/geometry/Point.js';
  import receiveLand from './receive-land.vue'
  import eidtLand from './eidtLand.vue'
  import nutritionLand from './nutritionLand.vue'
  import {VXETable} from 'vxe-table'

const userStore = useUserStore()
import landDetail from './landDetail.vue'
//注意：pinia解析出来的state也是可以调用，但会失去响应式，需要toRefs或者pinia自带storeToRefs
const farmcount = ref({farmLandTotal: 0, farmLandCount: 0})
const searchInfo = ref({page: 1, limit: 10, total: 0})
const landGroups = ref([])
const landTypes = ref([])
const landTags = ref([])
const tableData = ref([])
const openModel = ref(false)
const openModelType = ref(0)
const openDetails = ref(false)
const detailData = ref({})
const showDetail = ref(false)
const dropFarmLandId = ref('') // 下拉选择地块id
const dropFarmLandNo = ref('') // 下拉选择地块id
const dropFarmLandPic = ref('')
const loadingCount = ref(1)
const currentZoom= ref(5)
const clickRow = ref(null)
const showPop = ref(false)
const popObjct = ref({})
const refReceiveLand = ref(null)
const winWidth = ref(window.innerWidth-275)
let mapView =null
let graphicsLayer = null

onMounted(() => {
  getLandGroups()
  getDataList()
  getLandType()
  getLandTags()
})


const btnQuery = () => {
  searchInfo.value.page = 1
  getDataList()
}
const getDataList = async () => {
  let params = {
    ...searchInfo.value,
    companyId: userStore.userInfo.companyId,
    farmId: userStore.userInfo.farmId,
    landTagId: searchInfo.value.landTagId ? [searchInfo.value.landTagId] : null,
    order: 'desc',
    column: 'id',
  };
  let data = await getLandList(params)
  if (data.success) {
    tableData.value = data.data || []
    searchInfo.value.total = data.total || 0
  }
  let res = await getFarmCount({...params,...{farmLandName:searchInfo.value.farmLandName||null}})
  if (res.success) {
     farmcount.value = res.data || {}
  }
}

const changeMuen = (item) => {
    dropFarmLandId.value=''
    showDetail.value = false
    openModelType.value = item.type
    openModel.value = true
}

const pageChangeEvent = ({currentPage, pageSize}) => {
  searchInfo.value.page = currentPage
  searchInfo.value.limit = pageSize
  getDataList()
}
const zoomMap=(val)=>{
  currentZoom.value = val
  if(graphicsLayer){
        const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type == 'text')
        graphics.forEach(item => {item.visible = val > 17 ? true : false})
   }
   getClickData()
}

const pointerMove=(val)=>{
   getClickData()
}
const btnOpen =()=>{
  showDetail.value = true
  openDetails.value = false
}
const clickMap =(e,e2)=>{
     if(e2.results.length>0){
          e2.results.forEach(e3 => {
          let attrs = e3.graphic.attributes
         if(attrs?.class == "click-landMark") { 
           clickRow.value = attrs
           getClickData()
           showPop.value=true
         }
        })
      }
 }
const initMap = (map)=>{
     mapView = map
    getLandData() 
}

const btnDelAll = ()=>{
  refReceiveLand.value.btnDelAll()
}


//点击坐标点的弹出框数据
const getClickData = ()=>{
  if(!clickRow.value){return}
  let item = clickRow.value
  const mapPoint = new Point({longitude: item.locationLongitude,latitude: item.locationLatitude, spatialReference: {wkid: 4326}});
   const { x, y } = mapView.toScreen(mapPoint)
   item.x = x
   item.y = y
  const popOption = {
            title:item.farmLandNo,
            farmId:item.farmId,
            companyId:item.companyId,
            farmLandId:item.farmLandId,
            pic:item.pic,
            screenX: item.x+10,
            screenY: item.y+10,
            visible:true,
            mapX: item.longitude,
            mapY: item.latitude,
            btnText:'地块详情',
            footer:true,
            values: [
                {
                    label: '地块名称',
                    value: item.farmLandName
                },
                {
                    label: '地块面积',
                    value:  Number(item.mapAreaSize.toFixed(1))+'亩'
                },
                {
                    label: '地块类型',
                    value: item.landTypeName||'--'
                },
                {
                    label: '作物类型',
                    value: (item.cropName||'--')+','+(item.cropSeriesName||'--')
                }
            ],
            ...item
  }
  popObjct.value = popOption
}
  // 表格行单击处理事件
  const setMapData = (row)=>{
    dropFarmLandId.value = row.farmLandId
    dropFarmLandPic.value = row.pic
    dropFarmLandNo.value = row.farmLandNo
        mapView.set({
        zoom:18,
        center: [Number(row.locationLongitude), Number(row.locationLatitude)]
        })
    clickRow.value = row
    showPop.value = true
    getClickData()
  }
  
const getLandData =async ()=>{
let res = await getMinLandList({
        page:1,
        limit:1,
        farmId:userStore.userInfo.farmId,
        // farmLandStatus:0,
        companyId:userStore.userInfo.companyId
     })
  if(res.success){
    getLandTimes(res.total||1)
  }
}
const getLandTimes =async (farmLandCount)=>{
    let limit=500
     let params ={
      farmId:userStore.userInfo.farmId, 
      // farmLandStatus:0,
      companyId:userStore.userInfo.companyId}
        if(farmLandCount>0){
          let pageStr = (farmLandCount/limit).toFixed(3)
          let totalPage =0
          let page1 = pageStr.split('.')[0]
          let page2 = pageStr.split('.')[1]
          let pages =[]
          if(Number(page2)>0){
            totalPage = Number(page1)+1
          }
          for(let i=1;i<=totalPage;i++){
            pages.push({page:i,limit:limit})
          }
          pages.forEach(async (item)=>{
           let timeOut= setTimeout(async () => {
              let res =await getMinLandList({...params,...item})
              if(res.success){
                 clearTimeout(timeOut)
                 drawLandList(res.data||[])
              }  
            }, item.page==1?0:(item.page*1000));
      })
  }
}

//地块绘制到地图
const drawLandList = (dataList)=>{
  if(!graphicsLayer){
    graphicsLayer = new GraphicsLayer({ id:'factor-land-plot'});
  }else{
    //graphicsLayer.removeAll()
  }
    dataList.forEach((item,index)=>{
      if(item?.geom){
          const geo = WktToPolygon(item.geom, { wkid: 4326 });
          const newGeo = webMercatorUtils.geographicToWebMercator(geo)
          const polygon = new Graphic({
            geometry: newGeo,
            symbol: {
              type: 'simple-fill',
              color:'#25c28900',
              outline: {
                  color: '#25c289',
                  width: 1
              }
            },
            attributes: {
              class: 'click-landMark',
              farmLandId:item.farmLandId,
              ...item
            }
            })
            const textAreaStyle = {
                type: "text", 
                color: [255, 255, 255],
                haloColor: [0, 0, 0],
                haloSize: "1px",
                text: "",
                xoffset: 0,
                yoffset: 0,
                cursor: 'pointer',
                font: {
                  size: 10,
                  family: "PingFangSC",
                  weight: "bold"
                }
            }
            const AreaGeometry = polygon.geometry.extent.center
            const areaValue = Number(item.mapAreaSize.toFixed(1))
            let result = "";
            for (let i = 0, len = item.farmLandName.length; i < len; i++) {
              if (i % 8 === 0 && i != 0) result += '\n';
              result += item.farmLandName[i];
              }
            textAreaStyle.text = `${result}\n${areaValue}亩`
            const textAttr = { ...item, type: 'text' }
            const textAreaGraphic = new Graphic({
                geometry: AreaGeometry,
                symbol: textAreaStyle,
                attributes: textAttr,
                visible: currentZoom.value>17?true:false
              })
              graphicsLayer.add(polygon);
              graphicsLayer.add(textAreaGraphic)
              mapView.map.add(graphicsLayer)

      }
    })
  //画边形
  if(loadingCount.value==1){
    //定位
    loadingCount.value = 2
    setTimeout(() => {
        mapView.goTo(graphicsLayer.graphics.items);
    }, 500);
  }
}
const getLandType = () => {
  const params = {
    farmId: userStore.userInfo.farmId,
    limit: 100,
  };
  getLandTypeList(params).then((res) => {
    const list = res.data.map((group) => {
      return {
        label: group.landTypeName,
        value: group.landTypeId,
      };
    });
    landTypes.value = [{label: '全部', value: ''}, ...list];
  })
}


const getLandTags = () => {
  const params = {
    farmId: userStore.userInfo.farmId,
    companyId: userStore.userInfo.companyId,
    limit: 100,
  };
  getLandTagsList(params).then((res) => {
    const list = res.data.map((group) => {
      return {
        label: group.tagName,
        value: group.landTagId,
      };
    });
    landTags.value = [{label: '全部', value: ''}, ...list];
  })
}

const toNext =(row)=>{
      dropFarmLandId.value = row.farmLandId
      dropFarmLandPic.value = row.pic
      dropFarmLandNo.value =row.farmLandNo
      showDetail.value =true
}

const getLandGroups = () => {
  const params = {
    farmId: userStore.userInfo.farmId,
    companyId: userStore.userInfo.companyId,
    limit: 100,
  };
  getLandGroupList(params).then((res) => {
    const list = res.data.map((group) => {
      return {
        label: group.groupName,
        value: group.landGroupId,
      };
    });
    landGroups.value = [{label: '全部', value: ''}, ...list];
  })
}
 //移除地块
 const btnDel = async (row)=>{
    const info = await VXETable.modal.confirm({
        title:'您确认删除地块吗？',
        content:'删除后该地块不可见。'
    })
    if(info==='confirm'){
        let res = await releaseFarmland([row.farmLandId])
        if(res.success){
            VXETable.modal.message({ content: '删除成功', status: 'success'})
            getDataList()
        }else{
            VXETable.modal.message({ content: res.message, status: 'error'})
        }
    }
  }
 const eidtClick = async (row)=>{
    showDetail.value =false
    dropFarmLandId.value = row.farmLandId
    openModel.value = true
    openModelType.value = 2
  }

  
</script>
<style>
.select-search-view .el-select .el-input__inner {
  border: none;
  background: #f8f8f9;
}

.select-search-view .el-select .el-input__inner::placeholder {
  color: #333;
}
</style>
<style scoped lang="scss">
.land-view {
  height: calc(100vh - 120px);
  position: relative;

  .left-view-table {
    position: absolute;
    left: 20px;
    width: 300px;
    background-color: #fff;
    height: 100%;
    z-index: 999;
    height: calc(100vh - 90px);
    padding-top: 10px;
    top: 15px;

    .optate-search {
      display: flex;
      padding: 0 10px;
      margin: 0 0 5px 0;

      .scinput {
        flex: 1;
      }

    }

    .select-search-view {
      display: flex;
      justify-items: center;
      background-color: #f1f1f1;
      margin: 0 10px;
      border: 1px solid #dcdfe6;
    }
  }

  .map-view {
    height: calc(100vh - 120px);
    width: 100%;
  }

}
.land-detail {
  position: absolute;
  z-index: 195;
  width: auto;
  height: auto;
  left: 330px;
  top: 15px;
  bottom: 10px;
  right: 10px;
  background-color: #fff;
}
</style>
